var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var base64 = require('../../utils/Base64.js');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tc: 0,
    haibaoImgUrl: '',
    img_w: 300,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '海报生成中。。。',
    })

    var that = this;
    var tc = app.get_tc();
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          img_w: res.windowWidth - 30,
          tc: tc
        });
      }
    })

    wx.setNavigationBarTitle({
      title: options.title ? options.title : "专属海报",
    })

    var imgUrl = options.imgUrl ? base64.decode(options.imgUrl) : '';
    
    console.log("海报图片链接：" + imgUrl);
    that.setData({
      haibaoImgUrl: imgUrl,
    });
  },
  
  //监听图片加载完毕
  imageLoadfinish:function(){
    wx.hideLoading();
  },

  saveImage: function(e){
    console.log("formid: ", e.detail.formId);
    var that = this;
    app.saveFormId(e.detail.formId);//保存fromId
    
    var imgurl = this.data.haibaoImgUrl;
    console.log("imgurl: ", imgurl);
    imgurl = imgurl.replace(/^http:/, 'https:');
    console.log("imgurl2: ", imgurl);
    wx.downloadFile({
      url: imgurl,
      type: 'image',
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            wx.showToast({
              // title: '海报已保存' + res.errMsg,
              title: '海报已保存',
              icon: 'success'
            })
          },
          fail: function (e) {
            console.log(e);
            wx.showToast({
              title: '保存失败',
              icon: 'fail'
            });
          }
        })
      },
      fail: function (e) {
        console.log(e);
        wx.showToast({
          title: '下载图片失败' + JSON.stringify(e),
          icon: 'fail'
        });
      }
    });
  },
})